{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "neural-network-and-data-loading.ipynb",
      "version": "0.3.2",
      "provenance": [],
      "collapsed_sections": [],
      "toc_visible": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "metadata": {
        "id": "18AF5Ab4p6VL",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "##### Copyright 2018 Google LLC.\n",
        "\n",
        "Licensed under the Apache License, Version 2.0 (the \"License\");"
      ]
    },
    {
      "metadata": {
        "id": "crfqaJOyp8bq",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "you may not use this file except in compliance with the License.\n",
        "You may obtain a copy of the License at\n",
        "\n",
        "https://www.apache.org/licenses/LICENSE-2.0\n",
        "\n",
        "Unless required by applicable law or agreed to in writing, software\n",
        "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "See the License for the specific language governing permissions and\n",
        "limitations under the License."
      ]
    },
    {
      "metadata": {
        "id": "B_XlLLpcWjkA",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "# Training a Simple Neural Network, with PyTorch Data Loading\n",
        "\n",
        "_Dougal Maclaurin, Peter Hawkins, Matthew Johnson, Roy Frostig, Alex Wiltschko, Chris Leary_\n",
        "\n",
        "![JAX](https://raw.githubusercontent.com/google/jax/master/images/jax_logo_250px.png)\n",
        "\n",
        "Let's combine everything we showed in the [quickstart notebook](https://colab.research.google.com/github/google/jax/blob/master/notebooks/quickstart.ipynb) to train a simple neural network. We will first specify and train a simple MLP on MNIST using JAX for the computation. We will use PyTorch's data loading API to load images and labels (because it's pretty great, and the world doesn't need yet another data loading library).\n",
        "\n",
        "Of course, you can use JAX with any API that is compatible with NumPy to make specifying the model a bit more plug-and-play. Here, just for explanatory purposes, we won't use any neural network libraries or special APIs for builidng our model."
      ]
    },
    {
      "metadata": {
        "id": "-8OFzj9TqXof",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "!pip install https://storage.googleapis.com/jax-wheels/cuda92/jaxlib-0.1-py3-none-any.whl\n",
        "!pip install jax"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "OksHydJDtbbI",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "from __future__ import print_function, division, absolute_import\n",
        "import jax.numpy as np\n",
        "from jax import grad, jit, vmap\n",
        "from jax import random"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "MTVcKi-ZYB3R",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Hyperparameters\n",
        "Let's get a few bookkeeping items out of the way."
      ]
    },
    {
      "metadata": {
        "id": "-fmWA06xYE7d",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# A helper function to randomly initialize weights and biases\n",
        "# for a dense neural network layer\n",
        "def random_layer_params(m, n, key, scale=1e-2):\n",
        "  w_key, b_key = random.split(key)\n",
        "  return scale * random.normal(w_key, (n, m)), scale * random.normal(b_key, (n,))\n",
        "\n",
        "# Initialize all layers for a fully-connected neural network with sizes \"sizes\"\n",
        "def init_network_params(sizes, key):\n",
        "  keys = random.split(key, len(sizes))\n",
        "  return [random_layer_params(m, n, k) for m, n, k in zip(sizes[:-1], sizes[1:], keys)]\n",
        "\n",
        "layer_sizes = [784, 512, 512, 10]\n",
        "param_scale = 0.1\n",
        "step_size = 0.001\n",
        "num_epochs = 10\n",
        "batch_size = 32\n",
        "n_targets = 10\n",
        "params = init_network_params(layer_sizes, random.PRNGKey(0))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "BtoNk_yxWtIw",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Auto-batching predictions\n",
        "\n",
        "Let us first define our prediction function. Note that we're defining this for a _single_ image example. We're going to use JAX's `vmap` function to automatically handle mini-batches, with no performance penalty."
      ]
    },
    {
      "metadata": {
        "id": "7APc6tD7TiuZ",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "from jax.scipy.misc import logsumexp\n",
        "\n",
        "def relu(x):\n",
        "  return np.maximum(0, x)\n",
        "\n",
        "def predict(params, image):\n",
        "  # per-example predictions\n",
        "  activations = image\n",
        "  for w, b in params[:-1]:\n",
        "    outputs = np.dot(w, activations) + b\n",
        "    activations = relu(outputs)\n",
        "  \n",
        "  final_w, final_b = params[-1]\n",
        "  logits = np.dot(final_w, activations) + final_b\n",
        "  return logits - logsumexp(logits)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "dRW_TvCTWgaP",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Let's check that our prediction function only works on single images."
      ]
    },
    {
      "metadata": {
        "id": "4sW2A5mnXHc5",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# This works on single examples\n",
        "random_flattened_image = random.normal(random.PRNGKey(1), (28 * 28,))\n",
        "preds = predict(params, random_flattened_image)\n",
        "print(preds.shape)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "PpyQxuedXfhp",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# Doesn't work with a batch\n",
        "random_flattened_images = random.normal(random.PRNGKey(1), (10, 28 * 28))\n",
        "try:\n",
        "  preds = predict(params, random_flattened_images)\n",
        "except TypeError:\n",
        "  print('Invalid shapes!')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "oJOOncKMXbwK",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# Let's upgrade it to handle batches using `vmap`\n",
        "from jax.util import curry\n",
        "\n",
        "# The `vmap` function alone works like `map`, in that it will\n",
        "# apply a function across inputs.\n",
        "# However, let's curry vmap so that it returns a function\n",
        "# with the original function signature.\n",
        "curried_vmap = curry(vmap)\n",
        "\n",
        "# Make a batched version of the `predict` function\n",
        "batched_predict = curried_vmap(predict, in_axes=(None, 0))\n",
        "\n",
        "# `batched_predict` has the same call signature as `predict`\n",
        "batched_preds = batched_predict(params, random_flattened_images)\n",
        "print(batched_preds.shape)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "elsG6nX03BvW",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "At this point, we have all the ingredients we need to define our neural network and train it. We've built an auto-batched version of `predict`, which we should be able to use in a loss function. We should be able to use `grad` to take the derivative of the loss with respect to the neural network parameters. Last, we should be able to use `jit` to speed up everything."
      ]
    },
    {
      "metadata": {
        "id": "NwDuFqc9X7ER",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Utility and loss functions"
      ]
    },
    {
      "metadata": {
        "id": "6lTI6I4lWdh5",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "def one_hot(x, k, dtype=np.float32):\n",
        "  \"\"\"Create a one-hot encoding of x of size k.\"\"\"\n",
        "  return np.array(x[:, None] == np.arange(k), dtype)\n",
        "  \n",
        "def accuracy(params, images, targets):\n",
        "  target_class = np.argmax(targets, axis=1)\n",
        "  predicted_class = np.argmax(batched_predict(params, images), axis=1)\n",
        "  return np.mean(predicted_class == target_class)\n",
        "\n",
        "def loss(params, images, targets):\n",
        "  preds = batched_predict(params, images)\n",
        "  return -np.sum(preds * targets)\n",
        "\n",
        "@jit\n",
        "def update(params, x, y):\n",
        "  grads = grad(loss)(params, x, y)\n",
        "  return [(w - step_size * dw, b - step_size * db)\n",
        "          for (w, b), (dw, db) in zip(params, grads)]"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "umJJGZCC2oKl",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Data Loading with PyTorch\n",
        "\n",
        "JAX is laser-focused on program transformations and accelerator-backed NumPy, so we don't include data loading or munging in the JAX library. There are already a lot of great data loaders out there, so let's just use them instead of reinventing anything. We'll grab PyTorch's data loader, and make a tiny shim to make it work with NumPy arrays."
      ]
    },
    {
      "metadata": {
        "id": "gEvWt8_u2pqG",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "!pip install torch torchvision"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "94PjXZ8y3dVF",
        "colab_type": "code",
        "cellView": "both",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "import numpy as onp\n",
        "from torch.utils import data\n",
        "from torchvision.datasets import MNIST\n",
        "\n",
        "def numpy_collate(batch):\n",
        "  if isinstance(batch[0], onp.ndarray):\n",
        "    return onp.stack(batch)\n",
        "  elif isinstance(batch[0], (tuple,list)):\n",
        "    transposed = zip(*batch)\n",
        "    return [numpy_collate(samples) for samples in transposed]\n",
        "  else:\n",
        "    return onp.array(batch)\n",
        "\n",
        "class NumpyLoader(data.DataLoader):\n",
        "  def __init__(self, dataset, batch_size=1,\n",
        "                shuffle=False, sampler=None,\n",
        "                batch_sampler=None, num_workers=0,\n",
        "                pin_memory=False, drop_last=False,\n",
        "                timeout=0, worker_init_fn=None):\n",
        "    super(self.__class__, self).__init__(dataset,\n",
        "        batch_size=batch_size,\n",
        "        shuffle=shuffle,\n",
        "        sampler=sampler,\n",
        "        batch_sampler=batch_sampler,\n",
        "        num_workers=num_workers,\n",
        "        collate_fn=numpy_collate,\n",
        "        pin_memory=pin_memory,\n",
        "        drop_last=drop_last,\n",
        "        timeout=timeout,\n",
        "        worker_init_fn=worker_init_fn)\n",
        "\n",
        "class FlattenAndCast(object):\n",
        "  def __call__(self, pic):\n",
        "    return onp.ravel(onp.array(pic, dtype=np.float32))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "l314jsfP4TN4",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# Define our dataset, using torch datasets\n",
        "mnist_dataset = MNIST('/tmp/mnist/', download=True, transform=FlattenAndCast())\n",
        "training_generator = NumpyLoader(mnist_dataset, batch_size=32, num_workers=0)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "FTNo4beUvb6t",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# Get the full train dataset (for checking accuracy while training)\n",
        "train_images = onp.array(mnist_dataset.train_data).reshape(len(mnist_dataset.train_data), -1)\n",
        "train_labels = one_hot(onp.array(mnist_dataset.train_labels), n_targets)\n",
        "\n",
        "# Get full test dataset\n",
        "mnist_dataset_test = MNIST('/tmp/mnist/', download=True, train=False)\n",
        "test_images = np.array(mnist_dataset_test.test_data.numpy().reshape(len(mnist_dataset_test.test_data), -1), dtype=np.float32)\n",
        "test_labels = one_hot(onp.array(mnist_dataset_test.test_labels), n_targets)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "xxPd6Qw3Z98v",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Training Loop"
      ]
    },
    {
      "metadata": {
        "id": "X2DnZo3iYj18",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "import time\n",
        "\n",
        "for epoch in range(num_epochs):\n",
        "  start_time = time.time()\n",
        "  for x, y in training_generator:\n",
        "    y = one_hot(y, n_targets)\n",
        "    params = update(params, x, y)\n",
        "  epoch_time = time.time() - start_time\n",
        "\n",
        "  train_acc = accuracy(params, train_images, train_labels)\n",
        "  test_acc = accuracy(params, test_images, test_labels)\n",
        "  print(\"Epoch {} in {:0.2f} sec\".format(epoch, epoch_time))\n",
        "  print(\"Training set accuracy {}\".format(train_acc))\n",
        "  print(\"Test set accuracy {}\".format(test_acc))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "xC1CMcVNYwxm",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "We've now used the whole of the JAX API: `grad` for derivatives, `jit` for speedups and `vmap` for auto-vectorization.\n",
        "We used NumPy to specify all of our computation, and borrowed the great data loaders from PyTorch, and ran the whole thing on the GPU."
      ]
    }
  ]
}
